package com.btex.app.tools;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.btex.app.R;
import java.io.File;

/**
 * Created by wcx on 16/3/17.
 */
public class PrompManager {
    private Context cxt;
    public static PrompManager prompManager;

    private PrompManager(Context context) {
        this.cxt =context;
    }

    public static PrompManager getPrompManager(Context context) {
        if (prompManager == null) {
            prompManager = new PrompManager(context);
        }
        return prompManager;
    }


    /**
     * 显示更新提醒对话框
     */
    public  void showUpdateDialog(final Activity act, final String url){
        final AlertDialog.Builder builder = new Builder(cxt);//this不能改为getApplicationContext（）
        //builder.setCancelable(false);   //不能按返回键,用户体验差
        //给提示框添加返回监听事件
        builder.setOnCancelListener(new DialogInterface.OnCancelListener(){
            @Override
            public void onCancel(DialogInterface dialog) {
               act.finish();
            }
        });
        builder.setTitle(cxt.getString(R.string.prompt_update));
        builder.setMessage("有新版本了！！！！！");
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    final HttpHandler handler = new HttpUtils().download(url, "/sdcard/com.toubi.apk", true, false, new RequestCallBack<File>() {
                        @Override
                        public void onSuccess(ResponseInfo<File> responseInfo) {
//                            tvProgress.setText(cxt.getString(R.string.download_ovew));
                            installApk(responseInfo.result.getPath());
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {
                            super.onLoading(total, current, isUploading);
                            int progress = (int) (current * 100 / total);
//                            tvProgress.setText("正在下载:" + progress + "%");
                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                            Toast.makeText(cxt, cxt.getString(R.string.update_fail), Toast.LENGTH_SHORT).show();
                        }

                        /**
                         * 安装一个apk文件，调用系统安装应用PackageInstaller
                         * @param path 要安装的apk路径
                         */
                        private void installApk(String path) {
                            File file = new File(path);
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            intent.addCategory("android.intent.category.DEFAULT");
                            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                            cxt.startActivity(intent);
                        }

                    });


                } else {
                    Toast.makeText(cxt, "sd卡不可用，更新失败", Toast.LENGTH_SHORT).show();
                    act.finish();
                    return;
                }
            }
        });
        builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                act.finish();
            }
        });
        builder.show(); //显示对话框
    }
}
